package cn.iocoder.ny.module.mall.service.impl;

import cn.hutool.json.JSONException;
import cn.iocoder.yudao.module.system.constant.WeChatAppConstants;
import cn.iocoder.ny.module.mall.controller.admin.product.dto.MallProductDTO;
import cn.iocoder.ny.module.mall.controller.admin.product.dto.MallProductListDTO;
import cn.iocoder.ny.module.mall.controller.admin.product.vo.MallProductOrderVo;
import cn.iocoder.ny.module.mall.controller.admin.product.vo.MallProductPageVo;
import cn.iocoder.ny.module.mall.domain.*;
import cn.iocoder.ny.module.mall.domain.vo.MallProductVo;
import cn.iocoder.ny.module.mall.enums.MallProductEnum;
import cn.iocoder.ny.module.mall.mapper.MallProductMapper;
import cn.iocoder.ny.module.mall.mapper.MallProductSpecificationMapper;
import cn.iocoder.ny.module.mall.service.IMallConfigService;
import cn.iocoder.ny.module.mall.service.IMallProductCateGoryService;
import cn.iocoder.ny.module.mall.service.IMallProductService;
import cn.iocoder.ny.module.mall.service.IMallProductSpecificationSerivce;
import cn.iocoder.yudao.module.system.util.OkHttpUtils;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.validation.Validator;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;


/**
 * @author luchunhong
 * @date 2024/08/06/ 10:36
 * @description:
 */

@Service
public class MallProductServiceImpl extends ServiceImpl<MallProductMapper, MallProduct> implements IMallProductService {
    @Autowired
    private IMallProductSpecificationSerivce mallProductSpecificationSerivce;
    @Autowired
    private MallProductMapper mallProductMapper;
    @Autowired
    private IMallProductCateGoryService mallProductCateGoryService;
    @Autowired
    protected Validator validator;

    @Autowired
    private IMallConfigService mallConfigService;
    @Autowired
    private MallProductSpecificationMapper mallProductSpecificationMapper;
//
//    @Autowired
//    private QRCodeService qrCodeService;

    /**
     * 新增商品
     *
     * @param mallProductDTO
     * @return
     */
    @Override
    @Transactional
    public boolean addProduct(MallProductDTO mallProductDTO) throws JSONException, JsonProcessingException {
//        // 判断是否是最小的叶子节点
//        Long count = mallProductCateGoryService.lambdaQuery()
//                .eq(MallProductCategory::getParentId, mallProductDTO.getMallProduct().getCategoryId()).count();
//        if (count > 0) {
//            return false;
//        }
        Long tenantId = getLoginUser().getTenantId();
        Long count = lambdaQuery().eq(MallProduct::getTitle, mallProductDTO.getMallProduct().getTitle()).eq(MallProduct::getDelFlag, 0)
                .eq(MallProduct::getTenantId, tenantId).count();
        if (count > 0){
            throw new RuntimeException("产品标题已存在，无法更新");
        }
        // 保存到商品表以及规格表内
        saveInProduct(mallProductDTO);
        return true;
    }




    @Override
    @Transactional
    public Integer productCopy(MallProductDTO mallProductDTO) throws JSONException, JsonProcessingException {
        // 判断是否是最小的叶子节点
        Integer copyDecide = mallProductDTO.getCopyDecide();
//        Long count = mallProductCateGoryService.lambdaQuery()
//                .eq(MallProductCategory::getParentId, mallProductDTO.getMallProduct().getCategoryId()).count();
//        if (count > 0) {
//            return 0;
//        }
        switch (copyDecide) {
            // 不保存复制
            case 1:
                return 1;
            case 2:
                // 保存复制
                saveInProduct(mallProductDTO);
                return 2;
        }
        return null;
    }

    @Override
    public String makeerByproductId(String appId, String productId) {
        MallConfig mallConfig = mallConfigService.lambdaQuery().eq(MallConfig::getAppid, appId).one();
        String wxToken = getWXToken(appId, mallConfig.getSecret());

        // 请求 URL
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxToken;

        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page", "pages/shopping/index");
        // 构建 scene 参数，确保不超过 32 个字符
        String scene = "productId=" + productId;
        if (scene.length() > 32) {
            scene = scene.substring(0, 32);
        }
        params.put("scene", scene);
        params.put("env_version", "trial");
        params.put("check_path", false);

        // 将参数转换为 JSON 格式
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonParams = gson.toJson(params);

        HttpURLConnection connection = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 写入请求参数
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                // 将字节数组转换为 Base64 编码字符串
                return Base64.getEncoder().encodeToString(imageBytes);
            } else {
                System.out.println(responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    public List<MallProduct> queryProductDropDownByTenantId() {
        Long tenantId = getLoginUser().getTenantId();
        List<MallProduct> list = lambdaQuery().eq(MallProduct::getTenantId, tenantId).eq(MallProduct::getIsShow, 1).eq(MallProduct::getDelFlag, 0).list();
        return list;
    }

    @Override
    public MallProductOrderVo queryBySpecificationId(HashMap<String, Object> hashMap) {
        Object spectionId = hashMap.get("spectionId");
        MallProductOrderVo mallProductOrderVo = mallProductSpecificationMapper.queryBySpecificationId(Long.valueOf(spectionId.toString()));
        return mallProductOrderVo;
    }


    @Override
    public PageResult<MallProductVo> queryProductList(MallProductPageVo reqVO) {
//        Long tenantId = getLoginUser().getTenantId();
//        reqVO.setTenantId(tenantId);
        IPage<MallProductVo> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        mallProductMapper.queryMallProductList(page,reqVO);
        return new PageResult<>(page.getRecords(),page.getTotal());
    }


    private boolean isSpecificationExists(String title, MallSpecificationExport specificationExport, Integer categoryId) {

        List<MallProductVo> mallProductVos = mallProductMapper.selectProductReplay(title, categoryId, specificationExport.getSpecName());
        for (MallProductVo mallProductVo : mallProductVos) {
            if (ObjectUtils.isEmpty(mallProductVo)){
                return true;
            }
            return false;

        }
        return true;
    }



    /**
     * 查询列表
     *
     * @param
     * @return
     */


//    @Override
//    public PageResult<MallConfig> getConfigPage(MallConfigPageVo reqVO) {
//        IPage<MallConfig> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
//        mallConfigMapper.queryPage(page, reqVO);
//        return new PageResult<>(page.getRecords(),page.getTotal());
//    }
    /**
     * 根据ID查询
     *
     * @param mallProductListDTO
     * @return
     */
    @Override
    public MallProductVo queryByProductId(MallProductListDTO mallProductListDTO) {
        return mallProductMapper.queryByProductId(mallProductListDTO);
    }

    /**
     * 修改商品
     */
    @Override
    public int updateProductById(MallProductDTO mallProductDTO) {
        Long tenantId = getLoginUser().getTenantId();
        Long count = lambdaQuery()
                .eq(MallProduct::getTitle, mallProductDTO.getMallProduct().getTitle())
                .eq(MallProduct::getDelFlag, 0)
                .eq(MallProduct::getTenantId, tenantId)
                .ne(MallProduct::getId, mallProductDTO.getMallProduct().getId())
                .count();
        if (count > 0){
            throw new RuntimeException("产品标题已存在，无法更新");
        }
        boolean b = updateProduct(mallProductDTO);
        if (b) {
            return 0;
        }
        return 1;
    }


    /**
     * 根据ID删除
     * @return
     */
    @Override
    @Transactional
    public boolean deleteProductById(MallProductDTO mallProductDTOList) {
        // 提取所有商品的ID
        Long tenantId = mallProductDTOList.getTenantId();
        List<Long> ids = mallProductDTOList.getIds();


        boolean update = lambdaUpdate()
                .in(MallProduct::getId, ids).in(!ObjectUtils.isEmpty(tenantId),MallProduct::getTenantId, tenantId)
                .set(MallProduct::getDelFlag, 1)
                .set(MallProduct::getIsShow,0)
                .update();
        if (update) {
            mallProductSpecificationSerivce.lambdaUpdate()
                    .in(MallProductSpecification::getProductId, ids).in(!ObjectUtils.isEmpty(tenantId),MallProductSpecification::getTenantId, tenantId)
                    .set(MallProductSpecification::getDelFlag, 1)
                    .update();
            return true;
        }
        return false;
    }


    private boolean updateProduct(MallProductDTO mallProductDTO) {
        Long tenantId = getLoginUser().getTenantId();
        // 修改商品表
        MallProduct mallProduct = mallProductDTO.getMallProduct();
        // 处理JSON
        processingJson(mallProduct);

        // 更新商品表
        mallProductMapper.updateById(mallProduct);

        // 得到ProductId
        Long productId = mallProductDTO.getMallProduct().getId();
        // 通过productId来查询出当前商品下的所有的商品规格
        List<MallProductSpecification> existingSpecifications = mallProductSpecificationSerivce.lambdaQuery()
                .eq(MallProductSpecification::getProductId, productId).list();
        // 修改/删除商品规格表
        List<MallProductSpecification> newSpecifications = mallProductDTO.getMallProductSpecifications();
        Set<Long> newSpecificationIds = newSpecifications.stream()
                .filter(spec -> spec.getId() != null)
                .map(MallProductSpecification::getId)
                .collect(Collectors.toSet());

        // 标记已删除的规格
        for (MallProductSpecification existingSpecification : existingSpecifications) {
            if (!newSpecificationIds.contains(existingSpecification.getId())) {
                existingSpecification.setDelFlag(1);
                existingSpecification.setIsShow(0);
                mallProductSpecificationSerivce.updateById(existingSpecification);
            }
        }

        for (MallProductSpecification specification : newSpecifications) {
            // 若规格ID为空则新增
            if (ObjectUtils.isEmpty(specification.getId())) {
                specification.setProductId(productId);
                specification.setTenantId(tenantId);
                mallProductSpecificationSerivce.save(specification);
            } else {
                // 更新规格信息
                mallProductSpecificationSerivce.lambdaUpdate()
                        .eq(MallProductSpecification::getId, specification.getId())
                        .update(specification);
            }
        }
        return true;
    }




    private void saveInProduct(MallProductDTO mallProductDTO) throws JSONException, JsonProcessingException {
        // 保存到商品表内
        LoginUser loginUser = getLoginUser();
        MallProduct mallProduct = mallProductDTO.getMallProduct();
//        mallProduct.setCreateBy(username);
        // 处理JSON
        processingJson(mallProduct);
        System.out.println("AWEAWE"+mallProduct+"xxxx");
        save(mallProduct);

        // 保存到商品规格表内
        List<MallProductSpecification> mallProductSpecifications = mallProductDTO.getMallProductSpecifications();
        for (MallProductSpecification specification : mallProductSpecifications) {
            specification.setProductId(mallProduct.getId());
//            specification.setCreateBy(username);
            specification.setTenantId(mallProduct.getTenantId());
            //新增的销量默认为0
            specification.setVolume(0);
        }
        mallProductSpecificationSerivce.saveBatch(mallProductSpecifications);
    }

    private void processingJson(MallProduct mallProduct) {
        MallProductEnum.FORM_JSON.process(mallProduct);
        MallProductEnum.IMAGES.process(mallProduct);
    }

    @SneakyThrows
    private String getWXToken(String appid,String secret){
        String message = OkHttpUtils.builder().url(WeChatAppConstants.PHONETOKENURL)
                // 有参数的话添加参数，可多个
                .addParam("grant_type", "client_credential")
                .addParam("secret", secret)
                .addParam("appid", appid)
                //.addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                .async();
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        String access_token = String.valueOf(map.get("access_token"));
        if (null==access_token){
            throw  new Exception("小程序登录失败，请联系管理员");

        }
        return access_token;

    }


    //      if (success) {
//            mallProductSpecificationSerivce.lambdaUpdate()
//
//                    .eq(MallProductSpecification::getId, mallProductListDTO.getSpecificationId())
//                    .update();
//        return true;
//    }
//    @Override
//    public String importProudct(List<MallProductVo> productList, String operName) {
//        if (StringUtils.isNull(productList) || productList.isEmpty()) {
//            throw new ServiceException("导入的商品数据不允许为空！");
//        }
//        int successNum = 0;
//        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder failureMsg = new StringBuilder();
//
//        for (MallProductVo mallProductVo : productList) {
//            String categoryName = mallProductVo.getName();
//            MallProductCategory mallProductCategory = mallProductCateGoryService.lambdaQuery()
//                    .eq(MallProductCategory::getName, categoryName)
//                    .one();
//
//            // 检查商品规格
//            if (ObjectUtils.isEmpty(mallProductVo.getSpecificationExport())) {
//                failureNum++;
//                failureMsg.append("<br/>").append(failureNum).append("、商品 ").append(mallProductVo.getTitle()).append(" 的规格不允许为空！");
//                continue;
//            }
//
//            if (ObjectUtils.isEmpty(mallProductCategory)) {
//                failureNum++;
//                failureMsg.append("<br/>").append(failureNum).append("、分类 ").append(categoryName).append(" 不存在，无法新增");
//                continue;
//            }
//
//            try {
//                // 查询是否存在相同标题和分类的商品
//                List<MallProductVo> existingProducts = mallProductMapper.selectProductReplay(mallProductVo.getTitle(), mallProductCategory.getId(), null);
//                if (existingProducts.isEmpty()) {
//                    // 不存在就新增商品
//                    MallProduct mallProduct = new MallProduct();
//                    mallProduct.setTitle(mallProductVo.getTitle());
//                    mallProduct.setCategoryId(Long.valueOf(mallProductCategory.getId()));
//                    mallProduct.setImages(mallProductVo.getImages());
//                    mallProduct.setDescription(mallProductVo.getDescription());
//                    mallProduct.setSort(mallProductVo.getSort());
//                    mallProduct.setIsShow(mallProductVo.getIsShow());
//                    mallProduct.setTenantId(Long.valueOf("2"));
//                    mallProduct.setCreateBy(operName);
//                    mallProductMapper.insert(mallProduct);
//
//                    Long productId = mallProduct.getId();
//                    importSpecifications(mallProductVo.getSpecificationExport(), productId);
//
//                    successNum++;
//                    successMsg.append("<br/>").append(successNum).append("、商品 ").append(mallProductVo.getTitle()).append(" 及其规格导入成功");
//                } else {
//                    // 商品已存在，检查并新增不存在的规格
//                    for (MallProductVo existingProduct : existingProducts) {
//                        Long productId = existingProduct.getId();
//                        if (isSpecificationExists(mallProductVo.getTitle(), mallProductVo.getSpecificationExport(), mallProductCategory.getId())) {
//                            importSpecifications(mallProductVo.getSpecificationExport(), productId);
//                            successNum++;
//                            successMsg.append("<br/>").append(successNum).append("、商品 ").append(mallProductVo.getTitle()).append(" 的规格 ").append(mallProductVo.getSpecificationExport().getSpecName()).append(" 导入成功");
//                        } else {
//                            failureNum++;
//                            failureMsg.append("<br/>").append(failureNum).append("、商品 ").append(mallProductVo.getTitle()).append(" 的规格 ").append(mallProductVo.getSpecificationExport().getSpecName()).append(" 已存在");
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、商品 " + mallProductVo.getTitle() + " 导入失败：";
//                failureMsg.append(msg).append(e.getMessage());
//                log.error(msg, e);
//            }
//        }
//
//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，部分数据导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，所有数据已成功导入！共 " + successNum + " 条，数据如下：");
//        }
//        return successMsg.toString();
//    }
//
//    private void importSpecifications(MallSpecificationExport specificationExport, Long productId) {
//        MallProductSpecification mallProductSpecification = new MallProductSpecification();
//        mallProductSpecification.setProductId(productId);
//        mallProductSpecification.setSpecName(specificationExport.getSpecName());
//        mallProductSpecification.setPriceLining(specificationExport.getPriceLining());
//        mallProductSpecificationSerivce.save(mallProductSpecification);
//    }

    //        boolean success = mallProductSpecificationSerivce.updateBatchById()
//                .setSql("stock" + mallProductListDTO.getBuyCount())
//                .eq(MallProductSpecification::getId, mallProductListDTO.getSpecificationId())
//                .apply("stock >= {0}", mallProductListDTO.getBuyCount())
//                .update();


}